package org.example.controller;

import org.example.entity.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController // 表示返回JSON数据
@CrossOrigin // 解决跨域问题（前后端分离必加）
public class LoginController {

    @Autowired
    private UserService userService;

    // 处理GET请求（示例）
    @GetMapping("/login/get")
    public Map<String, Object> loginGet(String username, String password) {
        return checkLogin(username, password);
    }

    // 处理POST请求（推荐）
    @PostMapping("/login/post")
    public Map<String, Object> loginPost(@RequestParam String username, @RequestParam String password) {
        return checkLogin(username, password);
    }

    // 验证逻辑
    private Map<String, Object> checkLogin(String username, String password) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.login(username, password);
        if (user != null) {
            result.put("success", true);
            result.put("message", "登录成功");
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }
}